<template>
  <div class="mainBody">
    <div class="mainBody_left">
      <el-tree ref="basicTree"  :props="treeInfo.defaultTreeProps" accordion node-key="code" :highlight-current="true"
        :lazy="true" :load="getTreeData" @node-click="hanldeTreeClick" />
    </div>
    <div class="mainBody_right">
      <BasicSearch ref="basicSearch" :formItemList="formItemList" @handleSearch="handleSearch"
        @handleReset="handleReset">
        <template #btnOptions>
          <el-button type="primary" plain :icon="Plus" v-has-permission="'system:area:add'" @click="add">新增</el-button>
          <el-button type="primary" plain :icon="Edit" v-has-permission="'system:area:edit'" @click="edit">修改</el-button>
          <el-button type="primary" plain :icon="View" v-has-permission="'system:area:detail'" @click="detail">查看</el-button>
          <el-button type="primary" plain :icon="Delete" v-has-permission="'system:area:del'" @click="del">删除</el-button>
        </template>
      </BasicSearch>
      <STable ref="sTable" :dataSource="dataSource.tableData" :columns="columns" :total="dataSource.total"
        :loading="dataSource.loading" :tableProps="dataSource.tableProps" @onPageChange="handlePageChange"
        @handleSelection="handleSelectRows" :extraProps="dataSource.extraProps">
        
      </STable>
    </div>

    <AreaAlert v-if="isAlert" :isAlert="isAlert" :parentData="parentData" :flag="alertFlag" :info="currInfo" 
      @closeDialog="closeDialog"></AreaAlert>
  </div>
</template>
<script lang="ts" setup>
import {Plus,Edit,View,Delete} from '@element-plus/icons-vue'
import { DataType, ColumnsType } from "@components/common/Table/tableTypes";
import { UserTreeData, UserTreeProps } from "@components/common/BasicTree/treeTypes";
import { toTreeData, alertEditAndLook, removeData } from "@/utils";
import { UseFormItem, OptionsData } from "@components/common/BasicSearch/serchTypes";
import { roleTypeEnum, commonStateEnum } from "@/utils/staticData";

import AreaAlert from "./components/AreaAlert.vue";
import { getAreaTree, areaQuery, areaDel } from "@/request/apis/system/area";

/************************表格相关**********************/
//checkbox是否可用
const selectable = (row: any) => {
  return row.type !==1
}

let columns = ref<Array<ColumnsType>>([
  { title: "多选", type: 'selection', width: 65},
  { title: "序号", type: "index", width: 120 },
  { title: "区域名称", key: "areaName" },
  { title: "区域code", key: "code" },
  { title: "创建时间", key: "ctime" },
]);

// 表格参数
let dataSource = reactive({
  tableData: [] as Array<DataType>,
  loading: false,
  total: 0,
  tableProps: {
    "row-key": "id",
  },
  extraProps:{selectable:selectable,}
});

// 切换分页
function handlePageChange() {
  getData();
}

// 获取数据
function getData() {
  dataSource.loading = true;
  let params = {
    currentPage: sTable.value.current,
    pageSize: sTable.value.pageSize,
    pid: parentData.code ? parentData.code : 0, //父节点
    ...basicSearch.value.searchInfo
  };
  areaQuery(params)
    .then((res: Response) => {
      dataSource.tableData = res.data;
      dataSource.loading = false;
      dataSource.total = res.totalRecords;
    })
    .catch((err) => {
      dataSource.loading = false;
    });
}

// ---------------操作---------------
let isAlert = ref<boolean>(false);
const alertFlag = ref("");

let currInfo = reactive<object>({})

provide("handleCancel", closeDialog);
// 关闭弹框
function closeDialog(flag: number) {
  isAlert.value = false;
  if (flag == 1) {
    updateTreeData();
    getData();
  }
}

const selectionsRows = ref<Array<DataType>>([]);
// 获取选中的载体
function handleSelectRows(selection: Array<DataType>) {
  selectionsRows.value = selection;
}
// 删除
function delData() {
  let ids: any[] = []
  selectionsRows.value.map(item => {
    ids.push(item.id)
  })
  areaDel(ids).then(res => {
    updateTreeData();
    getData();
    ElMessage.success('删除成功')
  }).catch(err => {

  })
}

//新增操作
function add(){
  if (parentData.code) {      
    alertFlag.value = 'area_add';
    isAlert.value = true;
  } else {
    ElMessage.warning("请先选择左侧机构")
  }
}

//修改操作
function edit(){
  alertFlag.value = 'area_edit';
  if (alertEditAndLook(selectionsRows.value)) {
    currInfo = selectionsRows.value[0]
    isAlert.value = true;
  }
}

//查看操作
function detail(){
  alertFlag.value = 'area_look';
  if (alertEditAndLook(selectionsRows.value)) {
    currInfo = selectionsRows.value[0]
    isAlert.value = true;
  }
}
//删除按钮操作
function del(){  
  removeData(selectionsRows.value, delData)
}

/****************************左侧树**************************/
//#region
const loading = ref(true)
const basicTree = ref();
let treeInfo = reactive({
  defaultTreeProps: {
    label: "areaName",
    children: "children",
  } as UserTreeProps,
});
// 选中的父级区域
let parentData = reactive({});
function hanldeTreeClick(item: UserTreeData) {
  parentData = item;
  getData();
}
// 获取树形数据
function getTreeData(node, resolve, reject) {
  let id = 0
  if (node.data.code) {
    id = node.data.code
  }
  getAreaTree({id:id})
    .then((res: any) => {
      return resolve(res)
    })
    .catch((e)=>{return reject()});
}

// 更新指定节点数据
function updateTreeData() {
  getAreaTree({id:parentData.code})
    .then((res: any) => {
      //basicTree.value.updateKeyChildren(parentData.code, []) // 清空子节点
      basicTree.value.updateKeyChildren(parentData.code, res)
    });
}

//#endregion

/************************* 查询相关 **************************/
//#region
const sTable = ref();
const basicSearch = ref();

// 搜索条件
let formItemList = ref<Array<UseFormItem>>([
  { type: "input", label: "区域名称", prop: "name", maxlength: 20 }
]);

// 查询
function handleSearch() {
  sTable.value.setCurrentPage(1);
  sTable.value.setPageSize(10);
  getData();
}

// 重置
function handleReset() {
  sTable.value.setCurrentPage(1);
  sTable.value.setPageSize(10);
  basicTree.value.clearCheckedKeys();
  parentData = {};
  getData();
}
//#endregion

// 初始化
onMounted(() => {
});
</script>

<style scoped lang="scss">
.table_opt {
  margin-bottom: 10px;
}
</style>